package com.aps.demo.receiver;

import com.aps.demo.model.ProductionData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * JSON数据接收器
 * 负责从JSON文件或字符串中读取生产数据
 */
@Slf4j
@Component
public class JSONDataReceiver implements DataReceiver {
    
    private final ObjectMapper objectMapper;
    private final Validator validator;
    
    public JSONDataReceiver(ObjectMapper objectMapper, Validator validator) {
        this.objectMapper = objectMapper;
        this.validator = validator;
    }
    
    @Override
    public ProductionData receive() {
        throw new UnsupportedOperationException("请使用带参数的receive方法");
    }
    
    /**
     * 从JSON文件读取数据
     */
    public ProductionData receiveFromFile(String filePath) throws IOException {
        log.info("从文件读取JSON数据: {}", filePath);
        
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("文件不存在: " + filePath);
        }
        
        ProductionData data = objectMapper.readValue(file, ProductionData.class);
        
        // 验证数据
        ValidationResult validation = validate(data);
        if (!validation.isValid()) {
            throw new RuntimeException("数据验证失败: " + String.join(", ", validation.getErrors()));
        }
        
        log.info("JSON文件读取成功");
        return data;
    }
    
    /**
     * 从JSON字符串读取数据
     */
    public ProductionData receiveFromString(String jsonString) throws IOException {
        log.info("从字符串读取JSON数据");
        
        ProductionData data = objectMapper.readValue(jsonString, ProductionData.class);
        
        // 验证数据
        ValidationResult validation = validate(data);
        if (!validation.isValid()) {
            throw new RuntimeException("数据验证失败: " + String.join(", ", validation.getErrors()));
        }
        
        log.info("JSON字符串读取成功");
        return data;
    }
    
    /**
     * 从输入流读取数据
     */
    public ProductionData receiveFromStream(InputStream inputStream) throws IOException {
        log.info("从输入流读取JSON数据");
        
        ProductionData data = objectMapper.readValue(inputStream, ProductionData.class);
        
        // 验证数据
        ValidationResult validation = validate(data);
        if (!validation.isValid()) {
            throw new RuntimeException("数据验证失败: " + String.join(", ", validation.getErrors()));
        }
        
        log.info("JSON输入流读取成功");
        return data;
    }
    
    @Override
    public ValidationResult validate(ProductionData data) {
        log.info("开始验证生产数据...");
        
        Set<ConstraintViolation<ProductionData>> violations = validator.validate(data);
        
        if (violations.isEmpty()) {
            log.info("生产数据验证通过");
            return ValidationResult.success();
        } else {
            String[] errors = violations.stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .toArray(String[]::new);
            
            log.warn("生产数据验证失败: {}", String.join(", ", errors));
            return ValidationResult.failure(errors);
        }
    }
} 